package com.bizmda.bizsip.sample.source.controller;

import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.common.*;
import com.bizmda.bizsip.converter.Converter;
import com.bizmda.bizsip.source.api.SourceClientFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 史正烨
 */
@Slf4j
@RestController
public class SampleSource4Controller {
    private Converter converter = Converter.getSourceConverter("source4");
    private BizMessageInterface appInterface = SourceClientFactory
            .getAppServiceClient(BizMessageInterface.class,"/openapi/sink14");

    @PostMapping(value = "/source4", consumes = "application/xml", produces = "application/xml")
    public Object doService(@RequestBody String inMessage, HttpServletResponse response) {
        BizMessage outMessage = null;
        try {
            JSONObject jsonObject = this.converter.unpack(inMessage.getBytes());
            log.debug("解包后消息:\n{}", BizUtils.buildJsonLog(jsonObject));
            BizMessage<JSONObject> bizMessage = this.appInterface.call(jsonObject);
            log.debug("调用服务返回消息:\n{}",BizUtils.buildBizMessageLog(bizMessage));
            byte[] outData = this.converter.pack(bizMessage.getData());
            log.debug("打包后消息:\n{}",BizUtils.buildHexLog(outData));
            return new String(outData);
        } catch (BizException e) {
            return "Source API执行出错:"
                    + "\ncode:" + e.getCode()
                    + "\nmessage:" + e.getMessage()
                    + "\nextMessage:" + e.getExtMessage();
        }
    }
}